<?php
/**
 *make logges
 * @author dld.com
 * @version 1.0.0
 */
class LoggerD extends CApplicationComponent
{
	public $flag=false;
    public $model = ""; //数据库中的日志表对应的模型，或者如果$this->dbType是mongodb时，对应的collection,必须配置
	public $dbType = 'mongodb';
	public $enable = true;
	public $logEvents = array();//事件过滤数组，存在于此数组中的事件才会被记录.格式为 array('admin/vote/delete'=>'删除投票',)
	public $userType = 0; //用户类型，1表示为后台用户，2表示前台用户，0表示未知
	public $cacheId = '';


    public function __construct($model = ''){
        //parent::__construct();
		if($model){
            $this->model = $model;
			$this->init();
		}
	}

    public function init(){
        parent::init();
        if($this->dbType != 'mongodb' && $this->model && is_string($this->model)){
            $this->model = new $this->model();
		}
		if(isset(Yii::app()->controller->userType)){
		    $this->userType = Yii::app()->controller->userType;
		}
	}

    /* 
	*写日志
	*@param array $datas 对应与所给模型的属性及其值的数组
	*@param string $action 事件所对应的完整路由名，用于过滤，以确定哪些事件需要记录。空字符串表示不过滤，无论什么事件，都记录
	*@return bool 写日志成功返回true
    */
	public function logging($datas,$flag,$action = ''){ 
		
		$this->flag=$flag;
        if($action){
            if(!$this->filter($action)){
                return false;
		    }
		}
		
		if($this->dbType != 'mongodb' && is_object($this->model)){
            foreach($datas as $key=>$val){
                if(strpos($val,'^^') === 0){
                    $this->model->$key = $this->genData(substr($val,2));
				}
				else{
                    $this->model->$key = $val;
				}
			}
            $this->model->setIsNewRecord(true);
			if($this->model->save()){
				return true;
			}
		}
		elseif($this->dbType == 'mongodb' && $this->model){
            foreach($datas as $key=>$val){
            	
                if(strpos($val,'^^') === 0){
                    $datas[$key] = $this->genData(substr($val,2));
				}
			}
			if($datas){
				try{
                    $rs=Yii::app()->writer->insert($this->model,$datas);
					return true;
				}
				catch(Exception $e){
                    return false;
				}
			}
		}
		return false;
	}
    
	/*
    *日志过滤，验证完整路由名存在于LoggerD::logEvents中才进行记录
	*@param string $action 要验证的字段的值
	*@return bool
	*/
	public function filter($action){
        if(is_array($this->logEvents) && $this->logEvents){
		    if($action){
                if(array_key_exists($action,$this->logEvents)){
                    return true;
		        }
		    }
        }
		return false;
	}

    /*
     *自动数据完成，即用户在LoggerD::logging()中传进来的参数$datas中，如果希望其中的数据元素的值由LoggerD实例自动来生成，可以将其值写成“^^value”,如希望注册时的ip由LoggerD自动产生，则可写为array('reg_ip'=>'^^ip');"reg_ip"对应日志模型里的注册  ip字段名
	 *@param string $type 产生哪种类型的值
	 *@return string
	*/
	public function genData($type){
        switch($type){
            case 'ip':
                return Yii::app()->request->getUserHostAddress();
			case 'request_time':
				return $_SERVER['REQUEST_TIME'];
			case 'action':
			    return strtolower(Yii::app()->controller->getRoute());
			case 'userid':
				return $this->getAccountId();
			case 'sta':
				return $this->getStatus();
			case 'username':
				return $this->getAccountName();
			case 'event':
				return $this->getEventName();
			case 'usertype':
				return $this->userType;
			case 'request_data':
				return $this->getRequestData();
			default:
				return Yii::app()->request->getUserHostAddress();
		}
	}
	public function getStatus(){
		if($this->flag===false){
			return '异常';
		}else{
			return '正常';
		}
	}
    /*
     *获取当前登录账户id，默认为系统管理员账户，要用到的同志可以修改方法，添加其他类型的账户
	 *@return string
	*/
    public function getAccountId(){
        if($this->userType === 1){
           return Yii::app()->admin->getId();
		}
        if($this->userType === 2){
           return Yii::app()->frontuser->getId();
		}
		return 0;
	}
    /*
     *获取当前登录账户名，默认为系统管理员账户，要用到的同志可以修改方法，添加其他类型的账户
	 *@return string
	*/
    public function getAccountName(){
        if($this->userType === 1){
           return Yii::app()->admin->getStorage('username');
		}
        if($this->userType === 2){
           return Yii::app()->frontuser->getStorage('username');
		}
	}
    /*
     *获取事件名称，事件名称及其对应的路由在LoggerD::logEvents数组里
	 *@return strint
	*/
	public function getEventName(){
        $key = strtolower(Yii::app()->controller->getRoute());
		if($key){
		    if(isset($this->logEvents[$key])){
                return $this->logEvents[$key];
		    }
		}
		return 'unknown';
	}

    /*
     *获取需要做日志记录的事件集
	 *@return string
	*/
	public function getLogEvents(){
		$logEvents = array();
		/*$cacheid = isset(Yii::app()->params['models']['log']['cacheid'])?Yii::app()->params['models']['log']['cacheid']:'';
		if($cacheid && isset(Yii::app()->$cacheid)){
		    $logEvents = Yii::app()->$cacheid->get('log_events');
		}*/
		if($this->logEvents){
            return $this->logEvents;
		}
		if(file_exists(dirname(__FILE__).'/../config/logEvents.php')){
            $logEvents = include(dirname(__FILE__).'/../config/logEvents.php');
		}
		return $logEvents;
	}
	
	public function getRequestData(){
		return var_export($_REQUEST, true);
	}
}
?>